package com.ubhave.powertrackernof1;

import java.util.ArrayList;
import java.util.Date;

import com.ubhave.powertrackernof1.R;

import android.app.Activity;
import android.support.v4.app.FragmentActivity;
//import android.app.DialogFragment;
import android.support.v4.app.DialogFragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

//WARNING: After I had to add Multipart Questionnaire Support at the last minute this class is now a mess. It works ... but has redundant code and questionable implementation
//WARNING 2: Adding forGoal support has made this even more of a mess.
//WARNING 3: ... making whats here already Async hasn't helped either ...

public class QuestionnaireActivity extends FragmentActivity implements LoginDialogListener{
    
	Resources res;
	String[] questions;
	String[] labels;
	String[] multipartNames;
	String[] multipartTitles;
	LifeGuideConnector lgc;
	SharedPreferences settings;
	SharedPreferences.Editor editor;
	Bundle bundle;
	String page;
	String totalpages;
	String name;
	String intro;
	String questionsperpage;
	String scale;
	String type;
	String labelMode;
	String orientation;
	String title;
	String titleText;
	TextView titletv;
	
	String usr;
	String intervention;
	
	String multipart;
	int introOffset;
	String forGoal;
	String goal;
	
	int week;
	int day;
	int qday;
	
	Date currentDate;
	Date displayDate;
		
	PageSensorLogger psl;
	PageLogger pl;
	
	ArrayList<String> currentvalues;
	
	boolean submitting;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        
    	//StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        //StrictMode.setThreadPolicy(policy);
    	
    	super.onCreate(savedInstanceState);
    	
    	res = getResources();
    	    	    	
    	settings=PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    	editor = settings.edit();
		lgc = new LifeGuideConnector(settings);
		
		//Calculate week
		String[] startDateString = settings.getString("appStart", "").split("-");
		Date startDate = new Date(new Integer(startDateString[2]),new Integer(startDateString[1]),new Integer(startDateString[0]));
		currentDate = new Date();
						
		long diff = currentDate.getTime()-startDate.getTime();
		double daysDiff = Math.floor(new Double(diff)/new Double(1000*60*60*24));
		day = new Integer(new Double(daysDiff).intValue()+1);
				
		if(currentDate.getHours()<11)
			qday=day-1;
		else
			qday=day;
		
		displayDate = currentDate;
		//Change display date for atypical questionnaire timing (5pm-11am days)
		if(displayDate.getHours()<11)
			displayDate.setTime(displayDate.getTime()-(1000*60*60*24));
		
		Log.i("POWeR Tracker Special:", "QDAY DEBUG qday:"+qday+" day:"+day+" daysDiff:"+daysDiff+" diff:"+diff+" div:"+(new Double(diff)/new Double(1000*60*60*24))+" startDate:"+startDate+" currentDate:"+currentDate);
		
		week=new Double(Math.ceil(daysDiff/7.0)).intValue();
		
		usr = settings.getString("LifeGuideUser", "");
		intervention = settings.getString("LifeGuideInterventionId", "");
		
			
		//Grab Values from Bundle
		bundle = getIntent().getExtras();
		page = bundle.getString("page");
		name = bundle.getString("name");
		title = bundle.getString("title");
		titleText = bundle.getString("title");
		scale = bundle.getString("scale");
		type = bundle.getString("type");
		labelMode = bundle.getString("labelMode");
		orientation = bundle.getString("orientation");
		
		multipart = bundle.getString("multipart");
		
		forGoal=bundle.getString("forGoal");
		goal=bundle.getString("goal");
		
		//set submitting boolean - this will prevent multiple clicks of submit confusing the page the user is on
		submitting=false;
		
		if(settings.getBoolean("SensorsOn", false))    		
			psl = new PageSensorLogger(this);
		pl=new PageLogger(this, name);
		
		class AsyncLogAndRetrieve extends AsyncTask{

			@Override
			protected Object doInBackground(Object... params) {
				//Usage Log
				/*editor.putString("usageLog", settings.getString("usageLog", "")+params[0].getClass().getSimpleName()+"("+name+") "+new Date()+", ");
				editor.commit();
				if(!usr.equals("")&&!intervention.equals(""))
					lgc.postVar(intervention, usr, "user", "appUsageLog", settings.getString("usageLog", ""),settings.getString("authkey",""));
				else
					Log.i("POWeR Tracker: ", "Log fail usr: "+usr+" int: "+intervention);*/
        
				try{
					pl.makeLog();
				
					//Sensor Logging
					if(settings.getBoolean("SensorsOn", false)){
						psl.makeLog();
					}
				
					if(forGoal!=null){
						if(new Integer(forGoal)<4){
							String goalValue = lgc.getVar(intervention, usr, "user", "currentgoal"+forGoal,settings.getString("authkey",""));
							if(goalValue!=null){
								goal = goalValue;
								editor.putString("currentgoal"+forGoal, goalValue);
								editor.commit();
							}
						}
						else{
							String goalValue = lgc.getVar(intervention, usr, "user", "currentpagoal"+(new Integer(forGoal)-3),settings.getString("authkey",""));
							if(goalValue!=null){
								goal = goalValue;
								editor.putString("currentpagoal"+(new Integer(forGoal)-3), goalValue);
								editor.commit();
							}
						}
					}
				} catch (PowerTrackerInvalidAuthKeyException e) {
					invalidKey();
				}
				
				return null;
			}
			
			protected void onPostExecute(Object result) {
				updateTitleText();
		    }
		};
        new AsyncLogAndRetrieve().execute(this);
        
        //Set an intro offset if its not a multipart
		introOffset = 0;
        if(multipart==null)
        	introOffset=1;
		
        
        //Get Questions, Titles, Intros, and Names
		questions = res.getStringArray(res.getIdentifier(name+"_questions","array",getPackageName()));
		
		labels = res.getStringArray(res.getIdentifier(name+"_labels","array",getPackageName()));
		intro = res.getString(res.getIdentifier(name+"_intro","string",getPackageName()));
		multipartNames = res.getStringArray(R.array.questionnaireMultipart);
		multipartTitles = res.getStringArray(R.array.questionnaireMultipartTitles);
		
		
		if(bundle.getStringArrayList("values")==null){
			currentvalues=new ArrayList<String>();
			for(int i=0;i<questions.length;i++)
				currentvalues.add(i, null);
		}
		else
			currentvalues = bundle.getStringArrayList("values");
		
		
		questionsperpage = bundle.getString("questionsPerPage");
		
		totalpages=""+new Double(Math.ceil(new Double(questions.length+(introOffset))/new Integer(questionsperpage))+1).intValue();
		
		if(new Double(questions.length)%new Integer(questionsperpage)==0){
			totalpages=""+(new Integer(totalpages)-1);
		}
		else{
			Log.i("POWeR Tracker: ", ""+new Double(questions.length+1)%new Integer(questionsperpage));
		}
		
		
		if(goal==null&&forGoal!=null){
			if(new Integer(forGoal)<4){
				goal=settings.getString("currentgoal"+forGoal, "");
			}
			else{
				goal=settings.getString("currentpagoal"+(new Integer(forGoal)-3), "");
			}
		}
				
		ScrollView svmain = new ScrollView(this);
		
		LinearLayout llmain = new LinearLayout(this);
        llmain.setOrientation(llmain.VERTICAL);
        //
        //llmain.setBackgroundColor(Color.WHITE);
        //
        
        
        TextView dateView = new TextView(this);
        dateView.setText("For Day "+qday+": "+displayDate.getDate()+"-"+(displayDate.getMonth()+1)+"-"+(1990+displayDate.getYear()));
        dateView.setTextSize(15);
        dateView.setGravity(new Gravity().CENTER);
        dateView.setTextColor(Color.WHITE);
        llmain.addView(dateView);
        
        
        titletv = new TextView(this);
        if(forGoal!=null&&new Integer(forGoal)>0&&new Integer(forGoal)<7&&goal!=null)
        	titleText =  "For Goal: "+goal+" "+title;
        
        titletv.setText(titleText);
        
        titletv.setTextSize(20);
        //titletv.setTextColor(Color.rgb(88, 165, 255));
        llmain.addView(titletv);
        
        LayoutParams lp;
        
        if(new Integer(totalpages)>1){
        
        	LinearLayout llnav = new LinearLayout(this);
        	llnav.setOrientation(llmain.HORIZONTAL);
                
        	Button navBack = new Button(this);
        	navBack.setBackgroundDrawable(res.getDrawable(R.drawable.arrowleft));
        	lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1.0f);
        	navBack.setLayoutParams(lp);
        	if(!page.equals("1")){
        		navBack.setOnClickListener(new View.OnClickListener(){
					@Override
					public void onClick(View v) {
						navBack();				
					}
        		});        
        	
        	}
        	llnav.addView(navBack);
        
        	TextView pageNav = new TextView(this);
        	pageNav.setText(page+"/"+totalpages);
        	pageNav.setTextSize(12);
        	lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 10.0f);
        	pageNav.setLayoutParams(lp);
        	pageNav.setGravity(new Gravity().CENTER);
        	//pageNav.setTextColor(Color.rgb(88, 165, 255));
        	llnav.addView(pageNav);
        
        	Button navForward = new Button(this);
        	navForward.setBackgroundDrawable(res.getDrawable(R.drawable.arrowright));
        	lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1.0f);
        	navForward.setLayoutParams(lp);
        	if(!page.equals(totalpages)){
        		navForward.setOnClickListener(new View.OnClickListener(){
					@Override
					public void onClick(View v) {
						navForward();				
					}
        		});        
        	
        	}
        	llnav.addView(navForward);
        
        	llmain.addView(llnav);
        }
                       
        //
        if(page.equals("1")&&multipart==null){
        	TextView questionnaireIntro = new TextView(this);
        	//questionnaireIntro.setText(R.string.questionnaire_intro);
        	questionnaireIntro.setText(intro);
        	questionnaireIntro.setTextSize(15);
            llmain.addView(questionnaireIntro);
        }
        
        else{
			if(orientation.equals("H")){
				LinearLayout llhorScale = new LinearLayout(this);
								
				lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1.0f);
							
				TextView horScalel = new TextView(this);
				horScalel.setText(labels[0]);
				horScalel.setTextColor(Color.WHITE);
				horScalel.setGravity(new Gravity().LEFT);
				horScalel.setTextSize(15);
				horScalel.setLayoutParams(lp);
				//horScalel.setTextColor(Color.rgb(88, 165, 255));
    			llhorScale.addView(horScalel);
    			
    			TextView horScalec = new TextView(this);
    			horScalec.setText("<--->");
    			horScalec.setTextColor(Color.WHITE);
    			horScalec.setGravity(new Gravity().CENTER);
    			horScalec.setTextSize(15);
    			horScalec.setLayoutParams(lp);
    			//horScalec.setTextColor(Color.rgb(88, 165, 255));
    			llhorScale.addView(horScalec); 
    			
    			TextView horScaler = new TextView(this);
    			horScaler.setText(labels[1]);
    			horScaler.setTextColor(Color.WHITE);
    			horScaler.setGravity(new Gravity().RIGHT);
    			horScaler.setTextSize(15);
    			horScaler.setLayoutParams(lp);
    			//horScaler.setTextColor(Color.rgb(88, 165, 255));
    			llhorScale.addView(horScaler);
    			
    			llmain.addView(llhorScale);
			}
        	for(int i =0;i<new Integer(questionsperpage);i++){
        		if((i+((new Integer(page)-(1+introOffset))*new Integer(questionsperpage))) <= questions.length-1){	
        			TextView question = new TextView(this);
        			int currentq=((new Integer(page)-(1+introOffset))*new Integer(questionsperpage))+i;
        			question.setText(questions[currentq]);
        			question.setTextSize(15);
        			//question.setTextColor(Color.rgb(88, 165, 255));
        			llmain.addView(question);
    		        
        			lp = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 1.0f);
        			RadioGroup rg = new RadioGroup(this);
        			rg.setLayoutParams(lp);
        			
        			if(orientation.equals("H"))
        				rg.setOrientation(rg.HORIZONTAL);
        			else
        				rg.setOrientation(rg.VERTICAL);
    		
        			for(int o = 1; o<(new Integer(scale)+1); o++){
        				RadioButton opt = new RadioButton(this);
        				if(orientation.equals("H"))
        					opt.setText(""+o);
        				else
        					opt.setText(o+": "+labels[o-1]);
        				
        				opt.setTextSize(12);
        				opt.setTag(new Integer(i));
        				opt.setId(o);
        				opt.setOnClickListener(new View.OnClickListener(){
        					@Override
        					public void onClick(View v) {
        						RadioButton rb = (RadioButton)v;
        						String value="";
        						if(rb.getText().toString().indexOf(":")!=-1){
        							value = rb.getText().toString().substring(0,rb.getText().toString().indexOf(":"));
        						}
        						else{
        							value = rb.getText().toString();
        						}
        						radioButtonClicked(((new Integer(page)-(1+introOffset))*new Integer(questionsperpage))+(Integer)v.getTag(),value);				
        					}
        				});
        				
        				//opt.setTextColor(Color.rgb(88, 165, 255));
        				rg.addView(opt);
        				
        				if(currentvalues.size()>currentq&&currentvalues.get(currentq)!=null&&currentvalues.get(currentq).equals(""+o)){
        					opt.setChecked(true);
        					rg.check(o);
        				}
        				
        			}
    		
        			llmain.addView(rg);
        		
        		}
        	
        	}
        	
        	if(page.equals(totalpages)){
        		Button submit = new Button(this);
        		submit.setText("Save");
        		submit.setOnClickListener(new View.OnClickListener(){
        			@Override
 					public void onClick(View v) {
 						submit();
					}
        		});
        		llmain.addView(submit); 
        	 }
        	
        }
        
		svmain.addView(llmain);
        
        setContentView(svmain);
              
        
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        if(psl!=null)
        	psl.stopLocationSensing();
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        if(psl!=null)
        	psl.resumeLocationSensing();
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        	
    	switch (item.getItemId()) {
            case android.R.id.home:
                // app icon in action bar clicked; go home
                goHome();
                return true;
            case R.id.home:
                // app icon in options clicked; go home
            	goHome();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.o_menu, menu);
        return true;
    }
    
    public void goHome(){
    	Intent intent = new Intent(this, PowerTrackerActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }
    
    public void navBack(){
    	
    	Intent myIntent = new Intent(getBaseContext(), QuestionnaireActivity.class);
      	
    	myIntent.putExtra("page", ""+(new Integer(page)-1));
    	myIntent.putExtra("name", name);
    	myIntent.putExtra("title", title);
    	myIntent.putExtra("questionsPerPage", questionsperpage);
    	myIntent.putExtra("scale", scale);
    	myIntent.putExtra("type", type);
    	myIntent.putExtra("labelMode", labelMode);
    	myIntent.putExtra("orientation", orientation);
    	myIntent.putExtra("values", currentvalues);
    	if(multipart!=null)
    		myIntent.putExtra("multipart", multipart);
    	if(forGoal!=null)
			myIntent.putExtra("forGoal", forGoal);
    		
    	startActivity(myIntent);
    	
    }
    
    public void navForward(){
    	
    	Intent myIntent = new Intent(getBaseContext(), QuestionnaireActivity.class);
    	myIntent.putExtra("page", ""+(new Integer(page)+1));
    	myIntent.putExtra("name", name);
    	myIntent.putExtra("title", title);
    	myIntent.putExtra("questionsPerPage", questionsperpage);
    	myIntent.putExtra("scale", scale);
    	myIntent.putExtra("type", type);
    	myIntent.putExtra("labelMode", labelMode);
    	myIntent.putExtra("orientation", orientation);
    	myIntent.putExtra("values", currentvalues);
    	if(multipart!=null)
    		myIntent.putExtra("multipart", multipart);
    	if(forGoal!=null)
			myIntent.putExtra("forGoal", forGoal);
    	
    	startActivity(myIntent);
    	
    }
    
    public void radioButtonClicked(int tag, String val){
    	
    	currentvalues.set(tag, val);
    	    	
    }
    
    public void submit(){
    	
    	ConnectivityManager cm = (ConnectivityManager)PowerTrackerApplication.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = cm.getActiveNetworkInfo();
		if(ni!=null){		
    	
			boolean valid = true;
    		for(int i = 0;i<questions.length;i++){
    			if(currentvalues.get(i)==null){
    				valid=false;
    	    		break;
    			}
    		}
    		
    		if(valid&&!submitting){
    			submitting=true;
    			class AsyncQuestionnaireSubmit extends AsyncTask{

    				@Override
    				protected Object doInBackground(Object... params) {
    			
    					try{
    						if(multipart==null){
    							editor = settings.edit();
    							editor.putBoolean("QDone-"+name+week, true);
    							editor.commit();
    		
    							Intent myIntent = new Intent().setClass((Activity)params[0], QuestionnaireMenuActivity.class);
    							for(int i =0; i<questions.length; i++){
    								lgc.postVar(intervention, usr, "user", "Questionaire-"+name+"-"+qday+"-"+(i+1), currentvalues.get(i)+"",settings.getString("authkey",""));
    							}
    							startActivityForResult(myIntent, 0);
    						}
    						else if(multipartNames.length!=(new Integer(multipart)+1)){
    						
    							for(int i =0; i<questions.length; i++){
    								String submitName = name;
    								if(forGoal!=null)
    									submitName+="-Goal"+forGoal;
    								lgc.postVar(intervention, usr, "user", "Questionaire-"+submitName+"-"+qday+"-"+(i+1), currentvalues.get(i)+"",settings.getString("authkey",""));
    							}
    			
    			
    							if(forGoal!=null){
    								goal=null;
    								while(goal==null){
    									forGoal=""+(new Integer(forGoal)+1);
    									if(new Integer(forGoal)<4)
    										goal = lgc.getVar(intervention, usr, "user", "currentgoal"+forGoal,settings.getString("authkey",""));
    									else
    										goal = lgc.getVar(intervention, usr, "user", "currentpagoal"+(new Integer(forGoal)-3),settings.getString("authkey",""));
    									if(forGoal.equals("7")){
    										forGoal=null;
    										break;
    									}
    								}
    							}
    			
    			
    							int turnPage=1;
    							if(forGoal!=null)
    								turnPage=0;
    			
    			
    							Intent myIntent = new Intent(getBaseContext(), QuestionnaireActivity.class);
    							myIntent.putExtra("page", "1");
    							myIntent.putExtra("name", multipartNames[new Integer(multipart)+turnPage]);
    							myIntent.putExtra("orientation", "H");
    							myIntent.putExtra("questionsPerPage", "3");
    							myIntent.putExtra("type", "Likert");
    							myIntent.putExtra("scale", "7");
    							myIntent.putExtra("labelMode", "0");
    							myIntent.putExtra("title", multipartTitles[new Integer(multipart)+turnPage]);
    							myIntent.putExtra("multipart", ""+(new Integer(multipart)+turnPage));
    							if(forGoal!=null)
    								myIntent.putExtra("forGoal", forGoal);
    							if(goal!=null)
    								myIntent.putExtra("goal", goal);
    							startActivity(myIntent);
    						}
    						else{
    							editor = settings.edit();
    							editor.putBoolean("QDone-Daily-"+qday, true);
    							editor.commit();
    							for(int i =0; i<questions.length; i++){
    								String submitName = name;
    								if(forGoal!=null)
    									submitName+="-Goal"+forGoal;
    								lgc.postVar(intervention, usr, "user", "Questionaire-"+name+"-"+qday+"-"+(i+1), currentvalues.get(i)+"",settings.getString("authkey",""));
    							}
    			
    							Intent myIntent = new Intent(getBaseContext(), PowerTrackerActivity.class);
    							startActivity(myIntent);
    						}
    					
    					} catch (PowerTrackerInvalidAuthKeyException e) {
    						invalidKey();
    					}
    					return null;
    					
    				}
    				
    				
    			};
    			new AsyncQuestionnaireSubmit().execute(this);
    			
    			
    			
    		}
    		else if(submitting){
    			Toast.makeText(this, "Questionnaire page is saving, please wait a moment.", Toast.LENGTH_SHORT).show();
    		}
    		else if(!valid){
    			Toast.makeText(this, "Please answer all questions before moving on to the next page", Toast.LENGTH_SHORT).show();
    		}
    		
		
		}
		else {
			Toast.makeText(this, "You have no network connection. Please establish an internet connection before completeing your questionnaire.", Toast.LENGTH_SHORT).show();
		}
    	
    }
    
    public void updateTitleText(){    	
    	if(forGoal!=null&&new Integer(forGoal)>0&&new Integer(forGoal)<7&&goal!=null)
        	titleText =  "For Goal: "+goal+" "+title;
    	
    	titletv.setText(titleText);
    	
    	
    }
    
    public void invalidKey(){
		DialogFragment dialog = new LoginDialog();
		Bundle errorBundle = new Bundle();
	    errorBundle.putString("error", "Your Authentication Key is invalid, expired, or is missing. Please Log In.");
	    dialog.setArguments(errorBundle);
	    //dialog.show(this.getFragmentManager(), "LoginDialog");
	    dialog.show(this.getSupportFragmentManager(), "LoginDialog");
	}
    
  	@Override
	public void onLoginDialogPositiveClick() {
		// TODO Auto-generated method stub
  		Log.i("POWeR Tracker Special: ","Clicked OK");
  		finish();
  		startActivity(getIntent());
	}


	@Override
	public void onLoginDialogNegativeClick() {
		// TODO Auto-generated method stub
		Log.i("POWeR Tracker Special: ","Clicked Cancel");
		goHome();
	}
}